<template>
  <div class="shifts">
    <!--顶部标题-->
    <div class="content-top">
      <span>班次管理</span>
    </div>
    <!--左边二级侧边栏-->
    <div class="content-left active">
      <div class="menu-item">
        <router-link to="/shifts/shifts">班次管理</router-link>
      </div>
      <div class="menu-item">
        <router-link to="/shifts/tempShifts">临时班次调整</router-link>
      </div>
    </div>
    <!--右边内容-->
    <div class="content-right active">
      <div class="content-head">
        <div class="input-item fl flex flex-y-center">
          <span class="span-input fl"
            ><el-input
              v-model="params.className"
              placeholder="按班次名称搜索"
            ></el-input
          ></span>
        </div>
        <div class="input-item fl">
          <span class="span-input fl"
            ><el-button
              type="primary"
              @click="
                () => {
                  ;(pparams = Object.assign(
                    {pageNum: 1, pageSize: 15, workShift: 0},
                    params,
                  )),
                    FnSearch()
                }
              "
              >查询</el-button
            ></span
          >
        </div>

        <div class="input-item fr">
          <span class="span-input fl"
            ><el-button type="primary" @click="FnDelete"
              >批量删除</el-button
            ></span
          >
        </div>
        <div class="input-item fr">
          <span class="span-input fl"
            ><el-button
              style="background-color: #9c0; color: #fff;"
              @click="FnAdd"
              >新建班次</el-button
            ></span
          >
        </div>
      </div>
      <div class="content-table">
        <el-table
          v-loading="tableLoading"
          ref="dragTable"
          :data="tableData"
          row-key="id"
          border
          fit
          highlight-current-row
          style="width: 100%;"
          @selection-change="selectChange"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column label="班次名称">
            <template slot-scope="scope">
              <span>{{ scope.row['className'] }}</span>
            </template>
          </el-table-column>
          <el-table-column label="适用部门">
            <template slot-scope="scope">
              <span>{{
                scope.row['deptName'] ? scope.row['deptName'] : '--'
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="是否采用">
            <template slot-scope="scope">
              <div class="flex flex-y-center">
                <el-switch
                  v-model="scope.row['enableStatus']"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  @change="e => FnChange(e, scope.row)"
                >
                </el-switch>
                <span style="margin-left: 5px; vertical-align: middle;">{{
                  scope.row['enableStatus'] ? '采用' : '不采用'
                }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <el-button @click="FnMask({type: 'edit', content: scope.row})"
                >编辑</el-button
              >
              <el-button @click="FnMask({type: 'delete', content: scope.row})"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-if="total > 0" class="content-page">
        <el-pagination
          :current-page="params.pageNum"
          :page-sizes="[15, 50, 100, 200, 500, 1000, 5000, 10000, 50000]"
          :page-size="params.pageSize"
          :total="total"
          style="float: right; margin-top: 14px;"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="pageSizeChange"
          @current-change="pageNumChange"
        />
      </div>
    </div>

    <!--各种弹窗-->
    <Vmask :mask="mask" @FnMask="FnMask" />
  </div>
</template>
<script>
import Vmask from '@/components/vmask.vue'
import {tempShifts, dept} from '@/const/api'

export default {
  name: 'Shifts',
  components: {
    Vmask,
  },
  data() {
    return {
      params: {
        include: false,
        className: '',
      },
      pparams: {
        pageNum: 1,
        pageSize: 15,
        workShift: 0, // 查询普通班次的标识
      },
      tableLoading: false,
      tableData: [],
      multipleSelection: [],
      mask: {
        id: null,
        title: '',
        showMask: false,
        form: [
          {
            title: '班次名称',
            width: '',
            type: 'text',
            name: 'className',
            value: '',
            default: '',
            placeholder: '请填写班次名称',
            disabled: false,
            required: true,
          },
          {
            title: '简称',
            width: '',
            type: 'text',
            name: 'simpleName',
            value: '',
            default: '',
            placeholder: '比如：白、白班、建议至少一个字',
            disabled: false,
            required: true,
          },
          {
            title: '选择颜色',
            width: '',
            type: 'color',
            name: 'color',
            value: '',
            default: '',
            placeholder: '请填选择颜色',
            disabled: false,
            required: true,
          },
          {
            title: '适用部门',
            width: '',
            type: 'select',
            name: 'deptId',
            value: '',
            default: '',
            placeholder: '',
            disabled: false,
            required: true,
          },
          {
            title: '开始时间',
            width: '',
            type: 'datetime',
            name: 'a',
            value: '',
            default: '',
            placeholder: '请填写开始时间',
            disabled: false,
            required: true,
          },
          {
            title: '结束时间',
            width: '',
            type: 'datetime',
            name: 'b',
            value: '',
            default: '',
            placeholder: '请填写结束时间',
            disabled: false,
            required: true,
          },
        ],
        width: '28%',
        btnLoading: false,
      },
      total: 0,
      timeStart: new Date(),
    }
  },
  created() {
    window._this = this
    this.getDepartmentList()
    this.FnSearch()
  },
  methods: {
    async FnSearch() {
      let params = this.pparams
      this.tableLoading = true
      let {data, state, code, msg, count} = await this.$axios.$get(
        tempShifts('List'),
        {params},
      )
      if (state == this.ResCode) {
        this.tableLoading = false
        data && data.length
          ? (data.forEach((n1, i1) => {
              n1.enableStatus = n1.enableStatus == 1 ? true : false
            }),
            (this.tableData = data))
          : (this.tableData = [])
        this.total = count
      }
    },
    async getDepartmentList() {
      let {data, state, code, msg, count} = await this.$axios.$get(
        dept('getList'),
        {params: {id: 0}},
      )
      if (state == this.ResCode) {
        data &&
          data.length &&
          data.forEach((n1, i1) => {
            n1.label = n1.deptName
            n1.value = n1.id
          })
        this.mask.deptIdOptions = data
      }
    },
    FnMask(e) {
      console.log(e)
      let type = e.type
      let content = e.content ? JSON.parse(JSON.stringify(e.content)) : false
      let mask = this.mask
      let timeStart = this.timeStart
      let timeEnd = new Date()

      if (timeEnd - timeStart >= 1500) {
        if (type == 'cancel') {
          mask.showMask = false
          this.$utils.clearForm(mask.form)
        } else if (type == 'addShifts') {
          this.$utils.maskForm(content.form).then(
            async res => {
              res.startDay = this.$utils.parseTime(res.a).split(' ')[0]
              res.endDay = this.$utils.parseTime(res.b).split(' ')[0]
              res.startTime = this.$utils.parseTime(res.a).split(' ')[1]
              res.endTime = this.$utils.parseTime(res.b).split(' ')[1]
              res.workShift = 0 // 临时班次加的标识
              res.id = mask.id
              res.enableStatus = Number(mask.enableStatus)
              mask.btnLoading = true
              let {data, state, code, msg} = await this.$axios.$get(
                tempShifts('saveOrUpdate'),
                {params: res},
              )
              if (state == this.ResCode) {
                if (!mask.id) {
                  // 新增
                  this.$Message.success('添加成功')
                } else {
                  // 修改
                  this.$Message.success('修改成功')
                }
                this.mask.showMask = false
                this.$utils.clearForm(mask.form)
                this.FnSearch()
              } else {
                this.$Message.error(msg)
              }
              mask.btnLoading = false
            },
            err => {
              this.$Message.error(err)
            },
          )
        } else if (type == 'edit') {
          mask.showMask = true
          mask.addShifts = true
          mask.id = content.id // 有id表示新增
          mask.enableStatus = content.enableStatus
          mask.title = '编辑临时班次'
          this.$utils.maskForm(content, mask.form).then(res => {
            res.forEach((n1, i1) => {
              'a' == n1.name &&
                (n1.value = new Date(
                  content.startDay + ' ' + content.startTime,
                ))
              'b' == n1.name &&
                (n1.value = new Date(content.endDay + ' ' + content.endTime))
            })
            this.mask.form = res
          })
        } else if (type == 'delete') {
          const h = this.$createElement
          this.$msgbox({
            title: '删除提示',
            message: h('p', null, [
              h('span', null, '你确定删除该记录吗？'),
              h(
                'i',
                {style: 'color: teal; fontStyle: normal'},
                content.className,
              ),
            ]),
            showCancelButton: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            beforeClose: (action, instance, done) => {
              if (action === 'confirm') {
                instance.confirmButtonLoading = true
                instance.confirmButtonText = '删除中...'
                this.$axios
                  .$get(tempShifts('delWorkShift'), {params: {id: content.id}})
                  .then(res => {
                    if (res.state == this.ResCode) {
                      this.$Message.success('删除成功')
                      this.FnSearch()
                    } else {
                      this.$Message.error(res.msg)
                    }
                    instance.confirmButtonLoading = false
                    instance.confirmButtonText = '确定'
                    done()
                  })
              } else {
                done()
              }
            },
          }).then(action => {
            // done();
          })
        }

        this.timeStart = timeEnd
      }
    },
    FnAdd() {
      this.mask.showMask = true
      this.mask.addShifts = true // 新建班次的标识
      this.mask.id = null // 新建没有id
      this.mask.enableStatus = null
      this.mask.title = '新建班次'
    },
    selectChange(n) {
      this.multipleSelection = n
    },
    FnDelete() {
      if (!this.multipleSelection || !this.multipleSelection.length)
        return this.$Message.error('没有选中任何记录')
      let ids = this.multipleSelection.map(n1 => n1.id)
      const h = this.$createElement
      this.$msgbox({
        title: '删除提示',
        message: h('p', null, [
          h(
            'i',
            {style: 'color: teal; fontStyle: normal'},
            '是否要删除多条记录吗？',
          ),
        ]),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '删除中...'
            this.$axios
              .$get(tempShifts('delWorkShift'), {params: {id: ids.join(',')}})
              .then(res => {
                if (res.state == this.ResCode) {
                  this.$Message.success('删除成功')
                  this.FnSearch()
                } else {
                  this.$Message.error(res.msg)
                }
                instance.confirmButtonLoading = false
                instance.confirmButtonText = '确定'
                done()
              })
          } else {
            done()
          }
        },
      }).then(action => {
        // done();
      })
    },
    async FnChange(e, row) {
      let params = JSON.parse(JSON.stringify(row))
      params.enableStatus = Number(params.enableStatus)
      let {data, state, code, msg} = await this.$axios.$get(
        tempShifts('saveOrUpdate'),
        {params},
      )
      if (state == this.ResCode) {
        this.$Message({
          message: '修改成功',
          duration: 2000,
          type: 'success',
        })
      } else {
        this.$Message({
          message: msg,
          duration: 2000,
          type: 'error',
        })
      }
    },
    pageNumChange(e) {
      this.pparams.pageNum = e
      this.FnSearch()
    },
    pageSizeChange(e) {
      this.pparams.pageSize = e
      this.pparams.pageNum = 1
      this.FnSearch()
    },
  },
}
</script>

<style lang="less">
.shifts {
}
</style>
